import 'dart:math';

import 'package:flutter/material.dart';

void main(List<String> args) {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  var key = GlobalKey<_BoxState>();
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
      body: Box(key: key),
      floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
      floatingActionButton: ElevatedButton(
          onPressed: () {
            RenderBox box = key.currentContext?.findRenderObject() as RenderBox;
            //获取全局坐标
            print(box.localToGlobal(Offset.zero));

            //获取 Widget
            var w = key.currentWidget!;
            print(w.runtimeType);

            //获取 context
            var context = key.currentContext!;
            print('${context.size} size');

            //换颜色
            key.currentState?.changeColor();
          },
          child: const Text('换颜色')),
    ));
  }
}

class Box extends StatefulWidget {
  const Box({super.key});

  @override
  State<Box> createState() => _BoxState();
}

class _BoxState extends State<Box> {
  var color = Color.fromRGBO(
      Random().nextInt(255), Random().nextInt(255), Random().nextInt(255), 1);
  changeColor() {
    setState(() {
      color = Color.fromRGBO(Random().nextInt(255), Random().nextInt(255),
          Random().nextInt(255), 1);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Center(
        child: Container(
      width: 100,
      height: 100,
      color: color,
    ));
  }
}
